# this makefile is meant to be used when building the hello module outside
# the kernel tree
#
# It works as follows:
# 1) if run directly by us (using make), it will internally then
#    find out where the real kernel build directory is and
#    invoke the real kernel makefile from there (via make -C).
#    it will also pass this working directory as a parameter to the
#    kernel build system which will then recursively invoke this file again.

# are we being run directly? (KERNELRELEASE envvar will be empty if so)
ifeq ($(KERNELRELEASE),)
  # find out where kernel source tree is (assume that running kernel
  # is the kernel that we want to build against). after running 'make modules_install'
  # or extracting new distribution kernel, the 'build' symlink will point to the
  # directory under which the kernel source tree (partial or full) lives, so
  # we utilize that here.
  #
  # also, note that if you're not running the kernel that you're building the module
  # for, you can invoke make like this:
  # KERNELDIR=/path/to/target/kernel/build/directory make
  # (assuming you have a working build tree in that path)
  # If the variable has been defined, it won't be redefined below (?=)
  KERNELDIR ?= /lib/modules/$(shell uname -r)/build
  # we'll pass path to this directory to kernel build process so that it will
  # invoke as again (soon below)
  CURDIR := $(PWD)
  
  # explicitly define 'modules' as the 'default' target (since it's listed
  # first here). This is to guard from possible make breakage if you'll add
  # other make rules into this file later on
all: modules
  
  # define the 'modules' target so that it will call the kernel proper build with 'modules' target
modules:
	$(MAKE) -C $(KERNELDIR) M=$(CURDIR) modules

  # define 'modules_install' target in similar fahsion
modules_install:
	$(MAKE) -C $(KERNELDIR) M=$(CURDIR) modules_install

  # define clean target (note that we don't need to bother the kernel build
  # system for this)
clean:
	$(RM) *.o .depend .*.cmd *.ko *.mod.c Module.symvers
	$(RM) -R .tmp_versions

  # tell make that the above targets do not result in files whose names are
  # the targets.
.PHONY: all modules modules_install clean

  # internal packaging support (not released)
-include Makefile.sync

else
  # the kernel build system is executing this make, so we define
  # obj-m which will list the names of the resulting objects, each of which
  # will be prelinked into a .ko.
  # note that obj-m is defined as simple make variable, but could easily be
  # a recursive var as well (wouldn't matter in our use)
  obj-m := hello.o
  
endif
  